# -*- coding:utf-8 -*-
from flask import render_template, current_app, request, g

from . import index_blu
from ... import constants
from ...models import News, Category
from ...utils.common import get_user_info, get_category_info, get_hits_info
from ...utils.resonse import info_jsonfy
from ...utils.response_code import RET


@index_blu.route('/')
@get_user_info
@get_category_info
@get_hits_info
def index():
    user = g.user
    newsBasicList = g.newsBasicList
    categoryList = g.categoryList

    data = {
        "user": user.to_dict() if user else None,
        "newsBasicList": newsBasicList,
        "categoryList": categoryList
    }

    return render_template("news/index.html", data=data)


@index_blu.route("/favicon.ico")
def favicon():
    return current_app.send_static_file("news/favicon.ico")


@index_blu.route("/news_list", methods=["GET"])
def get_news_list():
    """获取新闻列表页"""
    # 获取参数
    categoryId = request.args.get("cid")
    page = request.args.get("page", 1)
    perPage = request.args.get("per_page", constants.OTHER_NEWS_PAGE_MAX_COUNT)

    try:
        page = int(page)
        perPage = int(perPage)
    except Exception as e:
        current_app.logger.error(e)
        return info_jsonfy(RET.PARAMERR, "参数错误")

    filters = []
    if categoryId:
        filters = [News.category_id == categoryId]

    try:
        paginate = News.query.filter(*filters, News.status == 0).order_by(News.create_time.desc()).paginate(page, perPage, False)
    except Exception as e:
        current_app.logger.error(e)
        return info_jsonfy(RET.DBERR, "数据库查询错误")

    newsList = paginate.items
    totalPage = paginate.pages
    currentPage = paginate.page

    newsDictList = [news.to_basic_dict() for news in newsList]

    data = {
        "totalPage": totalPage,
        "currentPage": currentPage,
        "newsDictList": newsDictList
    }

    return info_jsonfy(RET.OK, "查询成功", data)
